/**
 * User: Justin Akin
 * Twitter: @idointernet
 * Date: 7/13/12
 */
jpackage( "twc.utils", function() {

    this.AjaxUtil = {

        stringToJSON: function( str ) {
            try {
                return str == "" ? {} : eval('('+ str + ')');
            }
            catch(e){
                return str;
            }
        },

        jsonToString: function( json ) {

            var key, value, isArray, pre, post, result = [], type = typeof( json );

            if( type == "object" ) {
                isArray = json && json.constructor == Array;
                pre = isArray ? "[" : "{";
                post = isArray ? "]" : "}";

                for( key in json ) {

                    value = json[key];
                    type = typeof( value );

                    if( type == "string" ) {
                        value = '"' + value + '"';
                    }
                    else if( type == "object" && value != null ) {
                        value = this.jsonToString( value );
                    }

                    result.push( ( isArray ? "" : '"' + key + '":') + String( value ) );
                }

                result =  pre + result + post;
            }
            else if( type == "string" ) {
                result = '"' + json + '"';
            }

            return String( result );

        }

    }

});
/**
 */

jpackage( "twc.utils", function(){

    var AjaxUtil = this.AjaxUtil;
	var Base64Util = this.Base64Util;

    this.CookieUtil = {

        read: function( name, objectify, decode ) {
        	// First look for the cookie by its original name. If it doesn't exist, look for the cookie
        	// with session_ prefixed to the name. "session_" is prefixed to some cookie names if the cookie 
        	// is written with the deleteOnLogout flag set to true. See CookieUtil.write function
        	var val = this.readCookieByName(name, decode) || this.readCookieByName("session_" + name, decode) || "";
        	return objectify ? AjaxUtil.stringToJSON( val ) : val;
        },

        write: function( name, value, expiry, path, domain, deleteOnLogout ) {

            var date, cookie, expires, encoded;
           
            if( typeof( value ) == "object" ) {
                value = AjaxUtil.jsonToString( value );
            }
            
            // Prefix the cookie with "session_" so that it can be searched for when logging out and deleted
            if ( deleteOnLogout ) name = "session_" + name;
            
            if( expiry ) {
                date = new Date();
                date.setTime( date.getTime() + expiry );
                expires = "; expires=" + date.toGMTString();
            }
            else {
                expires = "";
            }

            if( !path ) path = "/";

            encoded = this.encode( value );
            cookie = name + "=" + encoded + expires + "; path=" + path;

            if( domain ) {
                cookie += "; domain=" + domain;
            }

            document.cookie = cookie;
            var doc = document.cookie;
            var cook = document.cookie;
        },

        erase: function( name ){
            this.write( name, "", -1000 );
            // "session_" is prefixed to some cookie names if the cookie is written with the
            // deleteOnLogout flag set to true. See CookieUtil.write function
            this.write( "session_" + name, "", -1000 );
        },

        encode: function( string ) {
        	//For debugging, in order to preview the cookie values, use this:
        	//return formatEncode( string );
        	
            return encodeURIComponent( formatEncode( Base64Util.encode(string) ) );
        },

        decode: function( string ) {
        	//For debugging, in order to preview the cookie values, use this:
        	//return formatDecode( string );
        	
            return Base64Util.decode( formatDecode( decodeURIComponent( string ) ) );
        },
        
        readCookieByName: function( name, decode ) {
        	
        	var pattern = name + "=.*[^;]";
            var regex = new RegExp( pattern, "i" );
            var match = regex.exec( document.cookie );
            var val;

            if( match && match.length > 0 ) {
                val = match[0].split( "=" )[1].split( ";" )[0];

                if (decode !== false)
                    val = this.decode( val );
            }
            
            return val;
        },
        
        checkIfCookiesEnabled: function() {
        	this.write("checkIfCookiesEnabled", "test");
        	
        	// if CookieUtil.read succeeds, cookies are enabled
        	if ( this.read('checkIfCookiesEnabled') ) {
        		this.erase('checkIfCookiesEnabled');
        		return true;
        	}
        	else {
        		return false;
        	}	
        }
    };



    this.CookieUtil.SECOND =  1000;
    this.CookieUtil.MINUTE = this.CookieUtil.SECOND * 60;
    this.CookieUtil.HOUR = this.CookieUtil.MINUTE * 60;
    this.CookieUtil.DAY = this.CookieUtil.HOUR * 24;
    this.CookieUtil.WEEK = this.CookieUtil.DAY * 7;
    this.CookieUtil.YEAR = this.CookieUtil.DAY * 365;

    var originals = [ '\\n', '\\r', '\&', '\>', '\<', '\"', '\,', '\,', '\'', '%' ];
    var replacements = [ '_nl_', '_brk_', '_amp_', '_arrow-r_', '_arrow-l_', '_dbl_', '_comma_', '_app_', '_per_' ];
    var length = originals.length;

    var formatEncode = function( string ) {
        string = string || "";
        for( var i = 0; i < length; i++ ) {
            string = string.replace( new RegExp( originals[i], 'g'), replacements[i] );
        }

        return string;
    };

    var formatDecode = function( string ) {
        string = string || "";
        for( var i = 0; i < length; i++ ) {
            string = string.replace( new RegExp( replacements[i], 'g'), originals[i] );
        }

        return string;
    };
});

/**
 */

jpackage( "twc.utils", function(){

    var AjaxUtil = this.AjaxUtil;
	var Base64Util = this.Base64Util;

    var storage;
    try {
    	storage = window.sessionStorage;
    }
    catch(e) {}

    this.StorageUtil = {

        read: function( name, objectify ) {
        	try {
	        	var val = storage.getItem( name )
	        	return objectify ? AjaxUtil.stringToJSON( val ) : val;
	        }
	        catch(e) { return null; }
	    },

        write: function( name, value ) {
            if ( typeof( value ) == "object" ) {
                value = AjaxUtil.jsonToString( value );
            }
            
            try {
            	storage.setItem(name, value);
            }
            catch(e) {}
        },

        erase: function( name ){
        	try {
        		storage.removeItem(name);
            }
            catch(e) {}
        },

        clear: function() {
            try {
            	storage.clear();
            }
            catch(e) {}
        }
    };

});

jpackage("twc.utils", function(){
    this.StringUtil = {

        /*Returns a phone number in the format of 123-456-7890*/
        formatPhoneNum: function(str){
            return ('' + str).replace(/(\d{3})(\d{3})(\d{4})/, "($1) $2-$3");
        },

        formatTitleCase: function(str){
            return ('' + str).replace(/\w\S*/g, function(txt){
                return txt.charAt(0).toUpperCase() + txt.substr(1).toLowerCase();
            });
        }
    };
});


